Functions

A function is a block of organised, reusable code that does one related job. Write it once, call it as often as you like.

Two Kinds of Functions

Kind Who wrote it Example
Built-in Already inside Python print(), int(), len(), sum()
User-defined You, with def add_numbers()

Creating a Function

# Program to illustrate the use of user-defined functions
def add_numbers(x, y):
sum = x + y
return sum

num1 = 5
num2 = 6
print("The sum is", add_numbers(num1, num2))

Output

The sum is 11
The rules are short. def starts the definition, the header always ends with a colon, the name follows the same rules as any identifier, and only the indented lines belong to the function.

Syntax

def <function name>([parameter1, parameter2, ...]):
set of instructions to be executed
[return <value>]
Anything inside [ ] is optional, so a function may take no parameters and may return nothing.

Calling a Function

def area(length, width):
return length * width

result = area(5, 8)
print("Area of Rectangle:")
print(result)

Output

Area of Rectangle:
40
The function only runs when it is called. Defining it just teaches Python the recipe.

Local Scope

def multiply_by_two():
number = 5
result = number * 2
print("Inside function:", result)

multiply_by_two()
print(result)

Output

Inside function: 10
NameError: name 'result' is not defined
result is born inside the function and dies with it, so the last line has nothing to print. Variables like this are said to be in local scope.

Global Scope

number = 10

def add_five():
result = number + 5
print("Inside function:", result)

add_five()
print("Outside function:", number)

Output

Inside function: 15
Outside function: 10
A variable declared outside every function is global, so it can be read from anywhere in the program.